//
//  SearchScenicVC.swift
//  LeTu
//
//  Created by g1 on 2024/1/14.
//

import UIKit

class SearchScenicVC: BaseViewController {

    private var viewModel = SearchScenicVM()
    
    var selectCity: ((String, Int) -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        eventHandle()
        getData()
        
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        searchBar.becomeSearch()
    }
    func eventHandle() {
        
        searchBar.searchHolder = { [weak self] keyword in
            MYLog("搜索的关键词是 ", keyword)
            guard let strongSelf = self else { return }
//            strongSelf.searchGoods(keyword: keyword)
        }
        resultView.selectKeywordBlock = { [weak self] keyword in
            guard let strongSelf = self else { return }
            strongSelf.searchBar.setKeyword("")
            strongSelf.searchGoods(keyword: keyword)
            strongSelf.view.endEditing(true)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(textFieldDidChange(_:)), name: UITextField.textDidChangeNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowNotification(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHideNotification(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    func getData() {
        viewModel.getHotSearchKeys { [weak self] dialog in
            
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                if dialog.code == 200 {
                    strongSelf.searchCollectionView.reloadData()
                }
            }
            
        }
        
        if viewModel.countryType == 0 {
            viewModel.getChinaCitys {  [weak self] dialog in
                
                guard let strongSelf = self else { return }
                DispatchQueue.main.async {
                    if dialog.code == 200 {
                        strongSelf.searchCollectionView.reloadData()
                    }
                }
            }
        } else {
            viewModel.getForeignCitys {  [weak self] dialog in
                
                guard let strongSelf = self else { return }
                DispatchQueue.main.async {
                    if dialog.code == 200 {
                        strongSelf.searchCollectionView.reloadData()
                    }
                }
            }
        }
        
    }
    // 搜索商品
    func searchGoods(keyword: String) {
        view.endEditing(true)
        kHistoryKeywordsManager.saveKeyword(keyword: keyword)
        
        guard let handle = selectCity else { return }
        handle(keyword, viewModel.countryType)
        backAction()
        
//        viewModel.updateItems()
//        searchCollectionView.reloadData()
//        show(SearchResultVC(keyword: keyword), sender: nil)
    }
    
    // MARK: - configUI
    func configUI() {

        searchCollectionView.delegate = self
        searchCollectionView.dataSource = self
        
        view.addSubview(searchBar)
        view.addSubview(searchCollectionView)
        view.addSubview(resultView)
        
        searchBar.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(Size.navigationBarHeight)
        }
        searchCollectionView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(searchBar.snp.bottom).offset(6)
        }
        
        searchCollectionView.register(headerClass: BaseEmptyHeaderCollectionReusableView.self)
        searchCollectionView.register(headerClass: SearchClassifyCollectionReusableView.self)
        searchCollectionView.register(headerClass: SearchSectionHeaderCollectionReusableView.self)
        searchCollectionView.register(headerClass: SearchCityCollectionReusableView.self)
        searchCollectionView.register(footerClass: BaseEmptyFooterCollectionReusableView.self)
        searchCollectionView.register(cellClass: SearchTagCollectionViewCell.self)
        searchCollectionView.register(cellClass: SearchAddressCollectionViewCell.self)
        searchCollectionView.register(cellClass: SearchCityCollectionViewCell.self)
        searchCollectionView.register(cellClass: BaseEmptyCollectionViewCell.self)
        
        searchBar.rightItemHolder = { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.backAction()
        }
        
    }
    private lazy var searchBar = SearchScenicNavBar(placeholder: "请输入城市名称".localized)
    private lazy var searchCollectionView: UICollectionView = {
        let flowLayout = AlignFlowLayout()
        flowLayout.direction = .start
        flowLayout.minimumLineSpacing = 10
        flowLayout.minimumInteritemSpacing = 10
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        let searchCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
        searchCollectionView.backgroundColor = .white
        searchCollectionView.showsVerticalScrollIndicator = false
        searchCollectionView.keyboardDismissMode = .onDrag
        return searchCollectionView
    }()
    private lazy var resultView: SearchResultView = {
        let navHeight = Size.navigationBarHeight
        let resultView = SearchResultView(frame: CGRect(x: 0, y: navHeight, width: screenWidth, height: screenHeight - navHeight - 0))
        resultView.isHidden = true
        return resultView
    }()
    
}

extension SearchScenicVC: UITextFieldDelegate {
    
    @objc func keyboardWillShowNotification(_ notification: Notification) {
        
        guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
        
        let navHeight = Size.navigationBarHeight
        let resultViewHeight = screenHeight - navHeight
        var frame = resultView.frame
        frame.size = CGSize(width: frame.width, height: resultViewHeight - keyboardSize.height)
        resultView.frame = frame
    }
    @objc func keyboardWillHideNotification(_ notification: Notification) {
        resultView.isHidden = true
    }
    @objc func textFieldDidChange(_ notification: Notification) {
        
        guard let textField = notification.object as? UITextField,let text = textField.text else { return resultView.isHidden = true }
        resultView.isHidden = text.count == 0
        
        guard text.count > 0 else { return }
        viewModel.searchKeywordAssociate(keyword: text) { [weak self] dialog in
            
            guard let strongSelf = self, let keywords = dialog.data as? [String] else { return }
            DispatchQueue.main.async {
                strongSelf.resultView.setInfo(keywords: keywords)
            }
        }
    }

}

extension SearchScenicVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        guard section < viewModel.sectionItems.count else { return CGSize(width: screenWidth, height: 32) }
        let item = viewModel.sectionItems[section]
        if item.title == "分类".localized {
            return CGSize(width: screenWidth, height: 36)
        } else {
            return CGSize(width: screenWidth, height: 44)
        }
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        guard section < viewModel.sectionItems.count else { return CGSize(width: screenWidth, height: 0.01) }
        let item = viewModel.sectionItems[section]
        return item.title == "热门城市".localized ? CGSize(width: screenWidth, height: 16) : CGSize(width: screenWidth, height: 0.01)
    }
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            
            if indexPath.section < viewModel.sectionItems.count {
                
                let item = viewModel.sectionItems[indexPath.section]
                
                if item.title == "分类".localized {
                    let header = collectionView.dequeueReusableViewHeader(SearchClassifyCollectionReusableView.self, indexPath: indexPath)
                    header.selectClassifyHandle = { [weak self] _ , index in
                        guard let strongSelf = self else { return }
                        strongSelf.viewModel.countryType = index
                        strongSelf.getData()
                    }
                    return header
                } else if item.title == "热门城市".localized || item.title == "搜索历史".localized {
                    let header = collectionView.dequeueReusableViewHeader(SearchSectionHeaderCollectionReusableView.self, indexPath: indexPath)
                    header.setInfo(sectionItem: item)
                    header.clickHolder = { [weak self] title in
                        guard let strongSelf = self else { return }
                        if title == "搜索历史".localized {
                            kHistoryKeywordsManager.clearKeywords()
                            strongSelf.searchCollectionView.reloadData()
                        }
                    }
                    return header
                }
                let footer = collectionView.dequeueReusableViewFooter(BaseEmptyHeaderCollectionReusableView.self, indexPath: indexPath)
                return footer
            } else {
                
                let header = collectionView.dequeueReusableViewHeader(SearchCityCollectionReusableView.self, indexPath: indexPath)
                header.setCityModel(viewModel.citys[indexPath.section - viewModel.sectionItems.count])
                return header
            }

        } else {
            let footer = collectionView.dequeueReusableViewFooter(BaseEmptyFooterCollectionReusableView.self, indexPath: indexPath)
            return footer
        }
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        guard indexPath.section < viewModel.sectionItems.count else { return CGSize(width: screenWidth, height: 58) }
        let item = viewModel.sectionItems[indexPath.section]
        if item.title == "分类".localized {
            return CGSize(width: screenWidth, height: 0.01)
        }else {
            var text = ""
            if item.title == "热门城市".localized {
                let cityModel = viewModel.hotKeywords[indexPath.item]
                text = LanguageManager.shared.currentLanguage == .zh ? cityModel.name:cityModel.englishName
            } else {
                text = viewModel.historys[indexPath.item]
            }
            return CGSize(width: text.widthWithLimit(CGSize(width: CGFloat(MAXFLOAT), height: 32), font: kSetPingFangRegular(14)) + 24, height: 32)
        }

    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return viewModel.sectionItems.count+viewModel.citys.count
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        guard section < viewModel.sectionItems.count else { return (section-viewModel.sectionItems.count) < viewModel.citys.count ? viewModel.citys[section-viewModel.sectionItems.count].cities.count : 0 }
        let item = viewModel.sectionItems[section]
        if item.title == "热门城市".localized {
            return viewModel.hotKeywords.count
        } else if item.title == "分类".localized {
            return 1
        }
        return viewModel.historys.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if indexPath.section < viewModel.sectionItems.count {
            let item = viewModel.sectionItems[indexPath.section]
            if item.title == "热门城市".localized {
                let cell = collectionView.dequeueReusableCell(SearchTagCollectionViewCell.self, indexPath: indexPath)
                let cityModel = viewModel.hotKeywords[indexPath.item]
                cell.setTag(tag: LanguageManager.shared.currentLanguage == .zh ? cityModel.name:cityModel.englishName)
                return cell
            } else if item.title == "搜索历史".localized {
                let cell = collectionView.dequeueReusableCell(SearchTagCollectionViewCell.self, indexPath: indexPath)
                cell.setTag(tag: viewModel.historys[indexPath.item])
                return cell
            }

            return collectionView.dequeueReusableCell(BaseEmptyCollectionViewCell.self, indexPath: indexPath)
        } else {
            if indexPath.item < viewModel.citys[indexPath.section - viewModel.sectionItems.count].cities.count {
                let cell = collectionView.dequeueReusableCell(SearchCityCollectionViewCell.self, indexPath: indexPath)
                cell.setCityModel(viewModel.citys[indexPath.section - viewModel.sectionItems.count].cities[indexPath.item])
                return cell
            } else {
                return collectionView.dequeueReusableCell(BaseEmptyCollectionViewCell.self, indexPath: indexPath)
            }
        }
        
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var keyword = ""
        if indexPath.section < viewModel.sectionItems.count {
            let item = viewModel.sectionItems[indexPath.section]
            
            guard item.title != "banner" else { return }
            if item.title == "热门城市".localized {
                let cityModel = viewModel.hotKeywords[indexPath.item]
                keyword = LanguageManager.shared.currentLanguage == .zh ? cityModel.name:cityModel.englishName
            } else {
                keyword = viewModel.historys[indexPath.item]
            }
        } else {
            if indexPath.item < viewModel.citys[indexPath.section - viewModel.sectionItems.count].cities.count {
                let city = viewModel.citys[indexPath.section - viewModel.sectionItems.count].cities[indexPath.item]
                keyword = LanguageManager.shared.currentLanguage == .zh ? city.name:city.englishName
            }
        }
        
        guard keyword.count > 0 else { return }
        searchGoods(keyword: keyword)
        
    }
    
}

